<style lang='scss' >
.user-info {
  margin: 10px;
  .u-size-default.data-v-3bf2dba7 {
    font-size: 15px;
    margin-top: 20px;
    height: 38px;
    line-height: 38px;
    width: 100%;
    color: #fff;
    background: #36adc1;
  }
}
</style>
<template>
  <view class="u-page user-info">
    <u-form :model="form" ref="uForm" label-width="100px">
      <u-form-item label="姓名" prop="name">
        <u-input v-model="form.name" placeholder="请输入姓名" />
      </u-form-item>
      <u-form-item label="学校" prop="schoolId">
        <div @click="showSchool = true">
          {{ form.schoolName || '请选择学校' }}
        </div>
        <u-select
          v-model="showSchool"
          mode="single-column"
          :list="schoolList"
          value-name="schoolId"
          label-name="schoolName"
          @confirm="schoolConfirm"
        ></u-select>
      </u-form-item>
      <u-form-item label="学院" prop="collegeId">
        <div @click="showCollege = true">
          {{
            form.collegeName ||
            (form.schoolId ? '请选择学院' : '必须先选择学校')
          }}
        </div>
        <u-select
          v-model="showCollege"
          mode="single-column"
          :list="collegeList"
          value-name="collegeId"
          label-name="collegeName"
          @confirm="collegeConfirm"
        ></u-select>
      </u-form-item>
      <u-form-item label="角色类型" prop="role">
        <u-radio-group v-model="form.role">
          <u-radio
            v-for="(item, index) in [{ key: '1', name: '教师' }]"
            :key="index"
            :name="item.key"
          >
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="学院邀请码" prop="schoolFlag">
        <u-input v-model="form.schoolFlag" placeholder="请输入学院邀请码" />
      </u-form-item>
      <u-form-item label="性别" prop="sex">
        <u-radio-group v-model="form.sex">
          <u-radio
            v-for="(item, index) in [
              { key: 'M', name: '男' },
              { key: 'F', name: '女' }
            ]"
            :key="index"
            :name="item.key"
          >
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="手机号" prop="phone">
        <u-input v-model="form.phone" placeholder="请输入手机号" />
      </u-form-item>
      <u-form-item label="邮箱" prop="mail">
        <u-input v-model="form.mail" placeholder="请输入邮箱" />
      </u-form-item>
    </u-form>
    <u-button type="primary" @click="submit">提交</u-button>
  </view>
</template>

<script>
import * as api from '../../common/api.js'

const required = (type = 'string') => ({
  required: true,
  type,
  message: '不能为空',
  trigger: ['change', 'blur']
})
export default {
  data() {
    return {
      showSchool: false,
      schoolName: '',
      showCollege: false,
      collegeName: '',
      form: {
        schoolId: '',
        schoolName: '',
        collegeId: '',
        collegeName: '',
        role: '1',
        name: '',
        sex: '',
        phone: '',
        mail: ''
      },
      schoolList: [],
      collegeList: [],
      rules: {
        name: [required()],
        collegeId: [required('number')],
        phone: [
          required(),
          {
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            trigger: ['blur']
          }
        ],
        role: [required('number')],
        schoolId: [required('number')],
        schoolFlag: [required()],
        sex: [required()],
        mail: [
          required(),
          {
            validator: (rule, value, callback) => {
              if (value) {
                return this.$u.test.email(value)
              }
            },
            message: '邮箱格式不正确',
            trigger: ['blur']
          }
        ]
      }
    }
  },
  async onLoad(option) {
    console.log(option.info)
    try {
      if (option.info) {
        this.form = JSON.parse(option.info)
      }
      this.schoolList = await api.getSchool()
      await this.getCollege()
    } catch (e) {
      console.log(e)
      wx.showModal({
        title: '获取失败',
        content: '请稍后再试',
        showCancel: false,
        confirmText: '确定'
      })
    } finally {
      wx.hideLoading()
      uni.stopPullDownRefresh()
    }
  },
  methods: {
    async getCollege() {
      if (this.form.schoolId) {
        this.collegeList = await api.getCollege(this.form.schoolId)
      }
    },
    schoolConfirm(e) {
      this.form.schoolName = e[0].label
      this.form.schoolId = e[0].value
      this.form.collegeName = ''
      this.getCollege()
    },
    collegeConfirm(e) {
      this.form.collegeName = e[0].label
      this.form.collegeId = e[0].value
    },
    submit() {
      this.$refs.uForm.validate(async (valid) => {
        if (valid) {
          const res = this.form.teacherId
            ? await api.updateTeacher(this.form)
            : await api.postTeacher(this.form)
          if (res !== 'error') {
            await api.updateUser({
              loginPhone: this.form.phone,
              openId: wx.getStorageSync('openId'),
              role: this.form.role,
              teacherId: this.form.teacherId || res
            })
            wx.setStorageSync('schoolId', this.form.schoolId)
            wx.switchTab({
              url: `/pages/User/User`,
              success: function (e) {
                var page = getCurrentPages().pop()
                if (page == undefined || page == null) return
                page.onLoad()
              }
            })
          }
        } else {
          console.log('验证失败')
        }
      })
    }
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  }
}
</script>